﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin.MP.AdvancedAPIs;
using chihuopig.IService;

namespace chihuopig.Web.Web.Controllers
{
    public class WeChatAppLoginController : Controller
    {
        ImemberService _imemberService;
        public WeChatAppLoginController
        (
            ImemberService imemberService
        )
        {
            _imemberService = imemberService;
        }
        public IActionResult Index()
        {
            return View();
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
           string Code= Request.Query["code"];
            OAuthAccessTokenResult token = OAuthApi.GetAccessToken("wxd4e326f09ae7cbc5", "86425e83d61e93f74fffa982e810d3c1", Code);
            // _logger.LogDebug($"用户已经同意了 OAuthAccessTokenResult ");
            OAuthUserInfo UserInfo = OAuthApi.GetUserInfo(token.access_token, token.openid);
            // _logger.LogDebug($"OAuthApi.GetUserInfo(token.access_token, token.openid) ");
            var findMember = _imemberService.FindOpenId(UserInfo.openid);
            if (findMember == null)
            {
                
                long id = _imemberService.Add(new Model.Member()
                {
                    Addtime = DateTime.Now,
                    city = UserInfo.city,
                    headimgurl = UserInfo.headimgurl,
                    money = 0.00m,
                    nickname = UserInfo.nickname,
                    openId = UserInfo.openid,
                    Sex = UserInfo.sex,
                    unionid = UserInfo.unionid

                });
                if (id > 0)
                {
                    context.Result = new JsonResult(UserInfo);
                }
                else
                {
                    context.Result = new ContentResult() { Content = "{\"success\":\"false\"}", ContentType = "application/json" };
                }


            }
            else
            {
                context.Result = new JsonResult(UserInfo);
            }

            
        }
    }
}